// 性能优化工具 - 修复版本
class PerformanceOptimizer {
  constructor() {
    this.slowFunctions = new Map()
    this.performanceLogs = []
    this.isMonitoring = false
    this.originalSetTimeout = null
    this.originalSetInterval = null
    this.originalRequestAnimationFrame = null
    this.init()
  }

  init() {
    // 保存原始函数引用
    this.originalSetTimeout = window.setTimeout
    this.originalSetInterval = window.setInterval
    this.originalRequestAnimationFrame = window.requestAnimationFrame
    
    // 拦截可能影响性能的全局函数
    this.interceptGlobalFunctions()
    
    // 监控资源加载
    this.monitorResourceLoading()
    
    // 监控内存使用
    this.monitorMemoryUsage()
    
    // 检测外部脚本
    this.detectExternalScripts()
    
    console.log('🚀 性能优化工具已启动')
  }

  // 拦截全局函数
  interceptGlobalFunctions() {
    const self = this

    // 监控 setTimeout
    window.setTimeout = function(...args) {
      const startTime = performance.now()
      const id = self.originalSetTimeout.apply(window, args)
      
      // 检查是否是慢函数 - 使用原始setTimeout避免递归
      self.originalSetTimeout(() => {
        const endTime = performance.now()
        const duration = endTime - startTime
        if (duration > 100) {
          self.logSlowFunction('setTimeout', duration, args[1])
        }
      }, 0)
      
      return id
    }

    // 监控 setInterval
    window.setInterval = function(...args) {
      const startTime = performance.now()
      const id = self.originalSetInterval.apply(window, args)
      
      // 检查是否是慢函数 - 使用原始setTimeout避免递归
      self.originalSetTimeout(() => {
        const endTime = performance.now()
        const duration = endTime - startTime
        if (duration > 100) {
          self.logSlowFunction('setInterval', duration, args[1])
        }
      }, 0)
      
      return id
    }

    // 监控 requestAnimationFrame
    window.requestAnimationFrame = function(callback) {
      const wrappedCallback = (timestamp) => {
        const startTime = performance.now()
        callback(timestamp)
        const endTime = performance.now()
        const duration = endTime - startTime
        
        if (duration > 16) { // 超过一帧的时间
          self.logSlowFunction('requestAnimationFrame', duration, callback.name)
        }
      }
      
      return self.originalRequestAnimationFrame.call(window, wrappedCallback)
    }
  }

  // 监控资源加载
  monitorResourceLoading() {
    const observer = new PerformanceObserver((list) => {
      for (const entry of list.getEntries()) {
        if (entry.entryType === 'resource') {
          const loadTime = entry.responseEnd - entry.requestStart
          if (loadTime > 1000) { // 超过1秒的资源
            this.logSlowResource(entry.name, loadTime, entry.transferSize)
          }
        }
      }
    })

    try {
      observer.observe({ entryTypes: ['resource'] })
    } catch (e) {
      console.warn('PerformanceObserver not supported')
    }
  }

  // 监控内存使用
  monitorMemoryUsage() {
    if (performance.memory) {
      this.originalSetInterval(() => {
        const memory = performance.memory
        const usedMB = Math.round(memory.usedJSHeapSize / 1024 / 1024)
        const totalMB = Math.round(memory.totalJSHeapSize / 1024 / 1024)
        
        if (usedMB > 100) { // 超过100MB
          this.logMemoryWarning(usedMB, totalMB)
        }
      }, 5000)
    }
  }

  // 检测外部脚本
  detectExternalScripts() {
    const scripts = Array.from(document.scripts)
    const externalScripts = scripts.filter(script => {
      return script.src && !script.src.includes(window.location.origin)
    })

    if (externalScripts.length > 0) {
      console.warn(`⚠️ 检测到 ${externalScripts.length} 个外部脚本，可能影响性能:`)
      externalScripts.forEach(script => {
        console.warn(`  - ${script.src}`)
        this.logExternalScript(script.src)
      })
    }

    // 监控新添加的脚本
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.tagName === 'SCRIPT' && node.src) {
            if (!node.src.includes(window.location.origin)) {
              console.warn(`⚠️ 检测到新的外部脚本: ${node.src}`)
              this.logExternalScript(node.src)
            }
          }
        })
      })
    })

    observer.observe(document.head, { childList: true })
  }

  // 记录慢函数
  logSlowFunction(functionName, duration, source) {
    const log = {
      type: 'slow-function',
      function: functionName,
      duration: Math.round(duration),
      source: source?.toString().substring(0, 100) || 'unknown',
      timestamp: Date.now()
    }

    this.performanceLogs.push(log)
    console.warn(`🐌 慢函数检测: ${functionName} 执行了 ${Math.round(duration)}ms`)
    
    // 如果是 detectPageLang 这类函数，提供特殊处理
    if (functionName.includes('detectPageLang') || functionName.includes('detect')) {
      this.handleLanguageDetectionIssue(log)
    }
  }

  // 记录慢资源
  logSlowResource(url, loadTime, size) {
    const log = {
      type: 'slow-resource',
      url: url,
      loadTime: Math.round(loadTime),
      size: size,
      timestamp: Date.now()
    }

    this.performanceLogs.push(log)
    console.warn(`🐌 慢资源检测: ${url.split('/').pop()} 加载了 ${Math.round(loadTime)}ms`)
  }

  // 记录内存警告
  logMemoryWarning(usedMB, totalMB) {
    const log = {
      type: 'memory-warning',
      usedMB: usedMB,
      totalMB: totalMB,
      timestamp: Date.now()
    }

    this.performanceLogs.push(log)
    console.warn(`💾 内存警告: 使用了 ${usedMB}MB / ${totalMB}MB`)
  }

  // 记录外部脚本
  logExternalScript(url) {
    const log = {
      type: 'external-script',
      url: url,
      timestamp: Date.now()
    }

    this.performanceLogs.push(log)
  }

  // 处理语言检测问题
  handleLanguageDetectionIssue(log) {
    console.warn('🔍 检测到语言检测性能问题，这通常来自浏览器扩展')
    console.warn('建议解决方案:')
    console.warn('1. 禁用不必要的翻译扩展')
    console.warn('2. 在浏览器设置中关闭自动语言检测')
    console.warn('3. 使用浏览器开发者工具检查扩展性能')
    
    // 提供优化建议
    this.suggestOptimizations()
  }

  // 提供优化建议
  suggestOptimizations() {
    const suggestions = [
      {
        title: '禁用浏览器扩展',
        description: '临时禁用翻译、语言检测等扩展，查看性能是否改善',
        action: () => {
          console.log('请手动在浏览器扩展管理页面禁用相关扩展')
        }
      },
      {
        title: '使用无痕模式',
        description: '在无痕模式下测试，排除扩展影响',
        action: () => {
          console.log('请使用 Ctrl+Shift+N (Chrome) 或 Ctrl+Shift+P (Firefox) 打开无痕窗口')
        }
      },
      {
        title: '清理浏览器缓存',
        description: '清理浏览器缓存和Cookie，重置浏览器状态',
        action: () => {
          console.log('请手动清理浏览器缓存')
        }
      },
      {
        title: '检查网络连接',
        description: '确保网络连接稳定，避免网络延迟影响',
        action: () => {
          console.log('请检查网络连接状态')
        }
      }
    ]

    console.log('💡 性能优化建议:')
    suggestions.forEach((suggestion, index) => {
      console.log(`${index + 1}. ${suggestion.title}: ${suggestion.description}`)
    })
  }

  // 获取性能报告
  getPerformanceReport() {
    const report = {
      timestamp: new Date().toISOString(),
      slowFunctions: this.performanceLogs.filter(log => log.type === 'slow-function'),
      slowResources: this.performanceLogs.filter(log => log.type === 'slow-resource'),
      memoryWarnings: this.performanceLogs.filter(log => log.type === 'memory-warning'),
      externalScripts: this.performanceLogs.filter(log => log.type === 'external-script'),
      summary: {
        totalSlowFunctions: this.performanceLogs.filter(log => log.type === 'slow-function').length,
        totalSlowResources: this.performanceLogs.filter(log => log.type === 'slow-resource').length,
        totalMemoryWarnings: this.performanceLogs.filter(log => log.type === 'memory-warning').length,
        totalExternalScripts: this.performanceLogs.filter(log => log.type === 'external-script').length
      }
    }

    return report
  }

  // 导出性能报告
  exportReport() {
    const report = this.getPerformanceReport()
    const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `performance-report-${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
  }

  // 开始监控
  startMonitoring() {
    this.isMonitoring = true
    console.log('🚀 开始性能监控')
  }

  // 停止监控
  stopMonitoring() {
    this.isMonitoring = false
    console.log('⏹️ 停止性能监控')
  }

  // 清除日志
  clearLogs() {
    this.performanceLogs = []
    console.log('🗑️ 清除性能日志')
  }
}

// 创建全局性能优化器实例
window.performanceOptimizer = new PerformanceOptimizer()

// 提供全局访问方法
window.getPerformanceReport = () => window.performanceOptimizer.getPerformanceReport()
window.exportPerformanceReport = () => window.performanceOptimizer.exportReport()
window.clearPerformanceLogs = () => window.performanceOptimizer.clearLogs()

// 自动检测 detectPageLang 问题
if (typeof window.detectPageLang === 'function') {
  console.warn('⚠️ 检测到 detectPageLang 函数，这通常来自浏览器扩展')
  console.warn('建议禁用相关扩展以提升性能')
}

// 监控页面加载性能
window.addEventListener('load', () => {
  const navigation = performance.getEntriesByType('navigation')[0]
  if (navigation) {
    const loadTime = navigation.loadEventEnd - navigation.fetchStart
    console.log(`📊 页面加载时间: ${Math.round(loadTime)}ms`)
    
    if (loadTime > 3000) {
      console.warn('⚠️ 页面加载时间过长，建议优化')
    }
  }
})

console.log('🔧 性能优化工具已加载')
console.log('💡 使用 getPerformanceReport() 查看性能报告')
console.log('💡 使用 exportPerformanceReport() 导出报告')
console.log('💡 使用 clearPerformanceLogs() 清除日志')